package crm8000.Controllers

import crm8000.services.PwBillService
import crm8000.services.PermissionService;
import crm8000.services.UserService;
import grails.converters.JSON

class PurchaseController {

	static allowedMethods = [pwbillList: 'POST', editPWBill: 'POST', deletePWBill: 'POST',
		editPWBillDetail: 'POST', pwBillDetailList: 'POST',
		pwBillInfo: 'POST', commitPWBill: 'POST', pwBillDetailInfo: 'POST',
		deletePWBillDetail: 'POST']

	PermissionService permissionService

	UserService userService

	PwBillService pwBillService

	def pwIndex() {
		if (!permissionService.hasPermission("2001")) {
			redirect controller: "home"
		}

		[loginUserName: userService.loginUserName]
	}

	def pwbillList() {
		def data = pwBillService.pwbillList()
		render data as JSON
	}

	def editPWBill() {
		def result = pwBillService.editPWBill(params)

		render result as JSON
	}
	
	def deletePWBill() {
		def result = pwBillService.deletePWBill(params.id)
		
		render result as JSON
	}

	def editPWBillDetail() {
		def result = pwBillService.editPWBillDetail(params)

		render result as JSON
	}

	def pwBillDetailList() {
		def data = pwBillService.pwBillDetailList(params.pwBillId)

		render(contentType: "application/json") {
			array {
				for (g in data) {
					goods id: g.id, goodsCode: g.goods.code, goodsName: g.goods.name,
					goodsSpec: g.goods.spec, unitName: g.goods.unit.name, goodsCount: g.goodsCount,
					goodsPrice: g.goodsPrice, goodsMoney: g.goodsMoney
				}
			}
		}
	}

	def pwBillInfo() {
		def user = userService.loginUser
		def pwBill = pwBillService.pwBillInfo(params.id)

		render(contentType: "application/json") {
			ref = pwBill?.ref
			supplierId = pwBill?.supplier?.id
			supplierName = pwBill?.supplier?.name
			warehouseId = pwBill?.warehouse?.id
			warehouseName = pwBill?.warehouse?.name
			bizUserId = user.id
			bizUserName = user.name
		}
	}
	
	def commitPWBill() {
		def result = pwBillService.commitPWBill(params.id)
		
		render result as JSON
	}
	
	def refreshPWBillInfo() {
		def data = pwBillService.refreshPWBillInfo(params.id)
		render(contentType: "application/json") {
			amount = data
		}
	}
	
	def pwBillDetailInfo() {
		def data = pwBillService.pwBillDetailInfo(params.id)
		
		render(contentType: "application/json") {
			goodsId = data.goods.id
			goodsCode = data.goods.code
			goodsName = data.goods.name
			goodsSpec = data.goods.spec
			goodsUnit = data.goods.unit.name
			goodsCount = data.goodsCount
			goodsPrice = data.goodsPrice
		}
	}
	
	def deletePWBillDetail() {
		def result = pwBillService.deletePWBillDetail(params.id)
		
		render result as JSON
	}
	
	/**
	 * 采购退货
	 * @return
	 */
	def prIndex() {
		if (!permissionService.hasPermission("2007")) {
			redirect controller: "home"
		}

		[loginUserName: userService.loginUserName]
	}
}
